SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO

/****** Object:  Stored Procedure dbo.DiasDeLic    Script Date: 01/11/2001 02:41:52 p.m. ******/
/****** Object:  Stored Procedure dbo.DiasDeLic    Script Date: 7/18/00 1:20:51 PM ******/
CREATE PROCEDURE [dbo].[spDiasDeLicencias2] 
@Agente int,
@P_FDesde datetime,
@P_FHasta datetime,
@P_CodLic int,
@P_HoC varchar(1)
AS

declare @MFA datetime
declare @MFB datetime
declare @RFA datetime
declare @RFB datetime
declare @RBaja varchar(1)
declare @RSitLab int
declare @ContDias int
declare @dhdiff int
declare @msg varchar(200)

DECLARE Licencias INSENSITIVE CURSOR FORSELECT ss.FechaAlta,ss.Baja,ss.FechaBaja,ss.SituacionLaboral FROM tb_SubServiciosAgentes ss, tb_ServiciosAgentes s 
where s.Agente=@agente and (ss.Baja='N' or ss.FechaBaja>=@P_FDesde) 
and ss.FechaAlta<@P_FHasta and licencia=@P_CodLic 
and s.idServicioAgente = ss.ServicioAgente Order by ss.FechaAltaFOR READ ONLY

OPEN Licencias

FETCH NEXT FROM Licencias INTO @RFA,@RBaja,@RFB,@RSitLab

-- Considera la posibilidad de Cursor Vacio
if @@FETCH_STATUS=0
	select @MFA=@RFA,@MFB=dateadd(day,-1,@RFA),@ContDias=0
else
	select @MFA=@P_FDesde,@MFB=dateadd(day,-1,@P_FDesde),@ContDias=0

if @RFA < @P_FDesde
	Select @RFA = @P_FDesde

-- Recorrido del Cursor (Proyeccion sobre X)
While @@FETCH_STATUS=0 
	BEGIN	
	if @RBaja='N' or @RFB>@P_FHasta
			select @RFB=@P_FHasta
	select @msg=" Dias "+convert(char,@ContDias)+" MFA="+convert(char,@MFA)+" MFB="+convert(char,@MFB)+" RFA="+convert(char,@RFA)+" RFB="+convert(char,@RFB)
	print @msg
	if @RFA>@MFB
			BEGIN
			if @P_HoC="C"
				select @ContDias=@ContDias+(DateDiff(day,@MFA,@MFB)+1)
			else
				BEGIN
				execute @dhdiff=spdifdiashabiles @MFA,@MFB
				select @ContDias=@ContDias+@dhdiff
				END
			select @MFA=@RFA,@MFB=@RFB
			END
	else
			BEGIN
			if  @RFB>@MFB 
				select @MFB=@RFB
			END
	
	FETCH NEXT FROM Licencias INTO @RFA,@RBaja,@RFB,@RSitLab	
	
	END

CLOSE Licencias
DEALLOCATE Licencias

if @P_HoC="C"
	select @ContDias=@ContDias+(DateDiff(day,@MFA,@MFB)+1)
else
	BEGIN
	execute @dhdiff=spdifDiasHabiles @MFA,@MFB
	select @ContDias=@ContDias+@dhdiff
	END

print cast(@contdias as varchar(3))

RETURN (@ContDias)








GO
